<?php

namespace vico\reservarBundle\Controller;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;

use vico\reservarBundle\Entity\Usuario;
use vico\reservarBundle\Form\UsuarioType;

/**
 * Usuario controller.
 *
 */
class UsuarioController extends Controller
{

    /**
     * Lists all Usuario entities.
     *
     */
    public function indexAction()
    {
        $em = $this->getDoctrine()->getManager();

        $entities = $em->getRepository('rsBundle:Usuario')->findAll();

        return $this->render('rsBundle:Usuario:index.html.twig', array(
            'entities' => $entities,
        ));
    }
    /**
     * Creates a new Usuario entity.
     *
     */
    public function createAction(Request $request)
    {
        $entity = new Usuario();
        $form = $this->createCreateForm($entity);
        $form->handleRequest($request);

        if ($form->isValid()) {
												$encoder = $this->get('security.encoder_factory')
																												->getEncoder($entity);
												$entity->setSalt(md5(time()));
												$passwordCodificado = $encoder->encodePassword(
																				$entity->getPassword(),
																				$entity->getSalt()
												);
												$entity->setPassword($passwordCodificado);

            $em = $this->getDoctrine()->getManager();
            $em->persist($entity);
            $em->flush();
											$this->get('session')->getFlashBag()->add('info',
											   'Â¡ Se ha generado un nuevousuario!'
				        );

            return $this->redirect($this->generateUrl('administracion_usuario_show', array('id' => $entity->getId())));
        }

        return $this->render('rsBundle:Usuario:new.html.twig', array(
            'entity' => $entity,
            'form'   => $form->createView(),
        ));
    }

    /**
    * Creates a form to create a Usuario entity.
    *
    * @param Usuario $entity The entity
    *
    * @return \Symfony\Component\Form\Form The form
    */
    private function createCreateForm(Usuario $entity)
    {
        $form = $this->createForm(new UsuarioType(), $entity, array(
            'action' => $this->generateUrl('administracion_usuario_create'),
            'method' => 'POST',
        ));

								$form->add('submit', 'submit', array('label' => 'AÃ±adir Usuario',
																'attr'=>array(
																						'class'=>'btn btn-xs btn-link',	
																),	
								));

        return $form;
    }

    /**
     * Displays a form to create a new Usuario entity.
     *
     */
    public function newAction()
    {
        $entity = new Usuario();
        $form   = $this->createCreateForm($entity);

        return $this->render('rsBundle:Usuario:new.html.twig', array(
            'entity' => $entity,
            'form'   => $form->createView(),
        ));
    }

    /**
     * Finds and displays a Usuario entity.
     *
     */
    public function showAction($id)
    {
        $em = $this->getDoctrine()->getManager();

        $entity = $em->getRepository('rsBundle:Usuario')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find Usuario entity.');
        }

        $deleteForm = $this->createDeleteForm($id);

        return $this->render('rsBundle:Usuario:show.html.twig', array(
            'entity'      => $entity,
            'delete_form' => $deleteForm->createView(),        ));
    }

    /**
     * Displays a form to edit an existing Usuario entity.
     *
     */
    public function editAction($id)
    {
        $em = $this->getDoctrine()->getManager();

        $entity = $em->getRepository('rsBundle:Usuario')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find Usuario entity.');
        }

        $editForm = $this->createEditForm($entity);
        $deleteForm = $this->createDeleteForm($id);

        return $this->render('rsBundle:Usuario:edit.html.twig', array(
            'entity'      => $entity,
            'edit_form'   => $editForm->createView(),
            'delete_form' => $deleteForm->createView(),
        ));
    }

    /**
    * Creates a form to edit a Usuario entity.
    *
    * @param Usuario $entity The entity
    *
    * @return \Symfony\Component\Form\Form The form
    */
    private function createEditForm(Usuario $entity)
    {
        $form = $this->createForm(new UsuarioType(), $entity, array(
            'action' => $this->generateUrl('administracion_usuario_update', array('id' => $entity->getId())),
            'method' => 'PUT',
        ));

								$form->add('submit', 'submit', array('label' => 'Editar',
																'attr'=>array(
																							'class'=>'btn btn-xs btn-link',	
																
																),	
								));

        return $form;
    }
    /**
     * Edits an existing Usuario entity.
     *
     */
    public function updateAction(Request $request, $id)
    {
        $em = $this->getDoctrine()->getManager();

        $entity = $em->getRepository('rsBundle:Usuario')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find Usuario entity.');
        }

        $deleteForm = $this->createDeleteForm($id);
        $editForm = $this->createEditForm($entity);
        $editForm->handleRequest($request);

        if ($editForm->isValid()) {
												$encoder = $this->get('security.encoder_factory')
																												->getEncoder($entity);
												$entity->setSalt(md5(time()));
												$passwordCodificado = $encoder->encodePassword(
																				$entity->getPassword(),
																				$entity->getSalt()
												);
												$entity->setPassword($passwordCodificado);
            $em->flush();
											$this->get('session')->getFlashBag()->add('info',
											   '¡Los datos del Usuario han sido actualizados! '
				        );

            return $this->redirect($this->generateUrl('administracion_usuario_edit', array('id' => $id)));
        }

        return $this->render('rsBundle:Usuario:edit.html.twig', array(
            'entity'      => $entity,
            'edit_form'   => $editForm->createView(),
            'delete_form' => $deleteForm->createView(),
        ));
    }
    /**
     * Deletes a Usuario entity.
     *
     */
    public function deleteAction(Request $request, $id)
    {
        $form = $this->createDeleteForm($id);
        $form->handleRequest($request);

        if ($form->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $entity = $em->getRepository('rsBundle:Usuario')->find($id);

         if (!$entity) {
          throw $this->createNotFoundException('Unable to find Usuario entity.');
         }

									$reservas = $em->getRepository('rsBundle:Booking')->findOneBy(
												array(
													'operator'=>$entity->getId()	
												)
									);
// 
									if(!$reservas){
										$user = $this->get('security.context')->getToken()->getUser();
										if($user->getName() != $entity->getName()){
											$em->remove($entity);
											$em->flush();
											$this->get('session')->getFlashBag()->add('info',
											'El usuario ha sido eliminado con exito'
											);
										}else{
											$this->get('session')->getFlashBag()->add('info',
												'ATENCION: No puede borrarse a si mismo. ACCION NO PERMITIDA'
											);
										}
									}else{
										$this->get('session')->getFlashBag()->add('info',
											'El usuario que está tratando de eliminar tiene reservasasignadas. Por favor, elimine dichas reservas o modifique el operario para dicha reserva, antes de proceder a eliminarlo'
										);
									}
        }

        return $this->redirect($this->generateUrl('administracion_usuario'));
    }

    /**
     * Creates a form to delete a Usuario entity by id.
     *
     * @param mixed $id The entity id
     *
     * @return \Symfony\Component\Form\Form The form
     */
    private function createDeleteForm($id)
    {
        return $this->createFormBuilder()
            ->setAction($this->generateUrl('administracion_usuario_delete', array('id' => $id)))
            ->setMethod('DELETE')
												->add('submit', 'submit', array('label' => 'Borrar',
																				'attr'=>array(
																									'class'=>'btn btn-xs btn-link',	
																				),	
												))
            ->getForm()
        ;
    }
}
